package com.umeox.watch.moto.dataservice.work;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.os.Looper;
import android.os.NetworkOnMainThreadException;

import androidx.annotation.NonNull;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

import com.umeox.moto.common.log.Logger;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Created by Rambo 2021/12/6
 * Describe:
 */
public class ScanWifiWork extends Worker {


    private Context mContext;

    public ScanWifiWork(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
        mContext = context;
    }

    @NonNull
    @Override
    public Result doWork() {
        WifiManager wifiManager = (WifiManager) mContext.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (Looper.getMainLooper().getThread().getId() == Thread.currentThread().getId()) {
            throw new NetworkOnMainThreadException();
        }
        // 使用定时器,每隔1秒获得一次信号强度值
        //当搜索到附近有可用的WIFI或者20秒后取消任务
        CountDownLatch downLatch = new CountDownLatch(1);
        final AtomicLong start = new AtomicLong();
        BroadcastReceiver mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Logger.i(">>>附近WIFI：" + wifiManager.getScanResults());
                Logger.i(">>>WIFI搜索耗时：" + (System.currentTimeMillis() - start.get()) / 1000 + "秒");
                downLatch.countDown();
            }
        };
        mContext.registerReceiver(mReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
        try {
            if (wifiManager.startScan()) {
                Logger.w(">>>开始扫描附近WIFI");
                start.set(System.currentTimeMillis());
                downLatch.await(15L, TimeUnit.SECONDS);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            mContext.unregisterReceiver(mReceiver);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Logger.w( ">>>扫描WIFI结束");
        return Result.success();
    }
}
